﻿// This code is released under the BSD license.
namespace PugLib.UnitTest
{
    #region

    using System;
    using System.Net;
    using System.Threading;
    using Extensions.Collections;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Threading;

    #endregion

    /// <summary>
    ///This is a test class for AsyncWrapperTest and is intended
    ///to contain all AsyncWrapperTest Unit Tests
    ///</summary>
    [TestClass]
    public class AsyncWrapperTest
    {
        /// <summary>
        ///A test for DoAsyncStatic
        ///</summary>
        public void DoAsyncStaticTestHelper()
        {
            Func<String, WebResponse> f = uri => WebRequest.Create(uri).GetResponse();
            String[] sites = {
                                 "http://yahoo.com", "http://google.com", "http://microsoft.com", "http://www.e128.info",
                                 "http://karpology.wordpress.com"
                             };
            sites.ForEach(address => f.DoAsync(address, PrintResponse(address)));

            Func<int, string> sleep = timeToSleep =>
                                          {
                                              Thread.Sleep(timeToSleep);
                                              return "Thread " + Thread.CurrentThread.ManagedThreadId + " slept " +
                                                     timeToSleep + " ms";
                                          };

            for (int i = 0; i < 16; ++i)
            {
                AsyncWrapper.DoAsyncStatic(sleep, 1, Console.WriteLine);
                sleep.DoAsync(1, Console.WriteLine);
            }
        }

        private static Action<WebResponse> PrintResponse(string address)
        {
            return
                resp => Console.WriteLine(String.Format("Thread {2}: {0}: ContentType= {1}", address, resp.ContentType,
                                                        Thread.CurrentThread.ManagedThreadId));
        }

        [TestMethod]
        public void DoAsyncStaticTest()
        {
            DoAsyncStaticTestHelper();
        }
    }
}